<script setup>
import { ref, watch,onMounted } from 'vue'
import { queryClazzsApi,addClazzApi,queryByIdApi,updateClazzApi,deleteClazzApi } from '@/api/clazz'
import { queryAllEmpApi } from '@/api/emp'
import { ElMessage,ElMessageBox } from 'element-plus'

const searchClazz = ref({
  name: '',
  begin: '',
  end: '',
  date: []
})
const clear = () => {
  searchClazz.value = {
    name: '',
    begin: '',
    end: '',
    date: []
  }
  search();
}

watch(() => searchClazz.value.date, (newValue, oldValue) => {
  if (searchClazz.value.date && searchClazz.value.date.length > 0) {
    searchClazz.value.begin = searchClazz.value.date[0];
    searchClazz.value.end = searchClazz.value.date[1];
  } else {
    searchClazz.value.begin = '';
    searchClazz.value.end = '';
  }
})

const clazzList = ref([
])

const handleSizeChange = (val) => {
  search();
}
const handleCurrentChange = (val) => {
  search();
}

const total = ref(0)

const search = async () => {
  const result = await queryClazzsApi(searchClazz.value.name,
  searchClazz.value.begin,
  searchClazz.value.end,
    currentPage.value,
    pageSize.value);
  if (result.code) {
    clazzList.value = result.data.rows;
    total.value = result.data.total;
  }
}

onMounted(() => {
  search()
  queryMaster();
})

const currentPage = ref(1)
const pageSize = ref(10)

const dialogVisible = ref(false)
const dialogTitle = ref('')
const clazz = ref({})
const empList= ref([])
const insertClazz = () => {
  dialogVisible.value = true;
  dialogTitle.value = '新增班级';
  clazz.value = {};
  if(clazzFormRef.value){
    clazzFormRef.value.resetFields();
  }
}

const queryMaster = async () => {
  const result = await queryAllEmpApi();
  if (result.code) {
    empList.value = result.data;
  }
}

const subjects = ([{ name: 'java', value: 1 }, { name: '前端', value: 2 },
                  { name: '大数据', value: 3 },{ name: 'Python', value: 4 },
                  { name: 'Go', value: 5 },{ name: '嵌入式', value: 6 }])

const save = async () => {
  if (!clazzFormRef) return
  await clazzFormRef.value.validate(async (valid, fields) => {
    if (valid) {//通过
      let result;
      if(clazz.value.id){
        result = await updateClazzApi(clazz.value);
      }else{
        result = await addClazzApi(clazz.value);
      }
      if (result.code) {
        dialogVisible.value = false;
        ElMessage.success('保存成功');
        search();
      } else {
        ElMessage.error(result.msg);
      }
    } else {//不通过
      ElMessage.error('表单效验不通过,请检查表单');
    }
  });
}

const selectById = async (id) => {
  const result = await queryByIdApi(id);
  if (result.code) {
    clazz.value = result.data;
    dialogVisible.value = true;
    dialogTitle.value = '修改班级信息';
    if(clazzFormRef.value){
    clazzFormRef.value.resetFields();
  }
  }else{
    ElMessage.error(result.msg);
  }
}

const clazzFormRef = ref();
//表单校验规则
const rules = ref({
  name: [
    { required: true, message: '请输入班级名称', trigger: 'blur' },
    { min: 4, max: 30, message: '用户名长度应在4到30个字符之间', trigger: 'blur' }
  ],
  room: [
    { required: false,  trigger: 'blur' },
    { min: 1, max: 20, message: '姓名长度应在1到20个字符之间', trigger: 'blur' }
  ],
  beginDate: [
    { required: true, message: '请选择开课日期', trigger: 'change' }
  ],
  endDate: [
    { required: true, message: '请选择结束日期', trigger: 'change' }
  ],
  subject: [
    { required: true, message: '请选择', trigger: 'change' }
  ],
});

const deleteById = async (id) => {
  ElMessageBox.confirm(
    '你确定要删除该班级吗?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then( async() => {
     const result = await deleteClazzApi(id);
     if(result.code){
      ElMessage.success('删除成功');
      search();
     }else{
      ElMessage.error(result.msg);
     }
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}
</script>

<template>
  <h1>班级管理</h1>
  <div class="container">
    {{ searchClazz }}
    <!-- 表单 -->
    <el-form :inline="true" :model="searchClazz" class="demo-form-inline">
      <el-form-item label="班级名称">
        <el-input v-model="searchClazz.name" placeholder="请输入班级名称" />
      </el-form-item>

      <el-form-item label="结课时间">
        <el-date-picker v-model="searchClazz.date" type="daterange" range-separator="到" start-placeholder="开始时间"
          end-placeholder="结束时间" value-format="YYYY-MM-DD" />
      </el-form-item>


      <el-form-item>
        <el-button type="primary" @click="search">查询</el-button>
        <el-button type="info" @click="clear">清空</el-button>
      </el-form-item>
    </el-form>

    <!-- 新增班级 -->
    <div class="button">
      <el-button type="primary" @click="insertClazz">新增班级</el-button>
    </div>

    <!-- 表格 -->
    <el-table :data="clazzList" border style="width: 100%">
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column prop="name" label="班级名称" width="250" align="center" />
      <el-table-column prop="room" label="班级教室" width="100" align="center" />
      <el-table-column prop="masterName" label="班主任" width="100" align="center" />
      <el-table-column prop="beginDate" label="开课时间" width="150" align="center" />
      <el-table-column prop="endDate" label="结课时间" width="150" align="center" />
      <el-table-column prop="status" label="状态" width="150" align="center" />
      <el-table-column prop="updateTime" label="最后操作时间" width="250" align="center" />
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button type="primary" size="small" @click="selectById(scope.row.id)">编辑</el-button>
          <el-button type="danger" size="small" @click="deleteById(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <br>
    <!-- 分页 -->
    <el-pagination v-model:current-page="currentPage" 
                   v-model:page-size="pageSize"
                   :page-sizes="[10, 20, 50, 100]"
                   layout="total, sizes, prev, pager, next, jumper"
                   :total="total" 
                   @size-change="handleSizeChange"
                   @current-change="handleCurrentChange" />

    <!-- 新增or修改表单 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle">
    {{ clazz }}
    <el-form :model="clazz" :rules="rules" ref="clazzFormRef" label-width="80px">
      <!-- 基本信息 -->
      <!-- 第一行 -->
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="班级名称" prop="name">
            <el-input v-model="clazz.name" placeholder="请输入班级名称，如：西安黑马JavaEE就业100期"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第二行 -->
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="班级教室" prop="room">
            <el-input v-model="clazz.room" placeholder="请填写班级教室"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第三行 -->
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="开课时间" prop="beginDate">
            <el-date-picker v-model="clazz.beginDate" type="date" style="width: 100%;" placeholder="请选择开课时间"
              format="YYYY-MM-DD" value-format="YYYY-MM-DD"></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第四行 -->
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="结课时间" prop="endDate">
            <el-date-picker v-model="clazz.endDate" type="date" style="width: 100%;" placeholder="请选择结课时间"
              format="YYYY-MM-DD" value-format="YYYY-MM-DD"></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第五行 -->
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="班主任">
            <el-select v-model="clazz.masterId" placeholder="请选择" style="width: 100%;">
               <!-- <el-option v-for="emp in empList" :label="emp.name" :value="emp.value" />  -->
               <el-option v-for="emp in empList" :label="emp.name" :value="emp.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第六行 -->
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="学科" prop="subject">
            <el-select v-model="clazz.subject" placeholder="请选择" style="width: 100%;">
              <el-option v-for="subject in subjects" :label="subject.name" :value="subject.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 底部按钮 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </span>
    </template>
  </el-dialog>              
  </div>
</template>

<style scoped>
.container {
  margin: 20px;
}

.button {
  margin-bottom: 20px;
}

.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>